package com.guli.secKill.interceptor;
/*
 * @Author 罗俊
 * @date 2020/12/2 - 3:19 下午
 *
 */

import com.guli.common.constant.AuthServerConstant;
import com.guli.common.constant.OrderConstant;
import com.guli.common.constant.ProductConstant;
import com.guli.common.to.MemberTo;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<MemberTo> MEMBER_TO_THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();

        MemberTo attribute = (MemberTo) session.getAttribute(AuthServerConstant.LOGIN_USER_SESSION);


        String skuId = request.getParameter("skuId");

        if (ObjectUtils.isEmpty(attribute)) {
            // 用户session中没有用户信息，跳转登陆
            // Ajax 不支持重定向
            response.sendRedirect(AuthServerConstant.LOGIN_URL + "?redirectUrl=" + ProductConstant.ITEM_DETAIL_PAGE_URL_PREFIX+skuId);
            return false;
        }


        if (ObjectUtils.isEmpty(attribute.getId())) {
            // 用户session中没有用户id，（没有登陆）
            response.sendRedirect(AuthServerConstant.LOGIN_URL + "?redirectUrl=" + ProductConstant.ITEM_DETAIL_PAGE_URL_PREFIX+skuId);
            return false;
        }

        MEMBER_TO_THREAD_LOCAL.set(attribute);

        return true;
    }
}
